package exam.model.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import exam.common.util.NullCheckUtil;

/**
 * <p>JdbcManager</p>
 * @author Phong
 * @version 16/5/2012
 * @param <T>
 */
public class JdbcManager<T> {
	/**
	 * session:Session
	 */
	public Session session;
	/**
	 * transaction:Transaction
	 */
	public Transaction transaction;
	
	/**
	 * query
	 */
	public Query query;
	
	/**
	 * beginTransaction
	 */
	public void beginTransaction() {
		if(NullCheckUtil.isNUll(session)) {
			session = HibernateSessionFactory.openSession();
		}
		transaction = session.beginTransaction();
	}
	
	/**
	 * commit
	 */
	public void commit() {
		transaction.commit();
	}
	
	/**
	 * rollBack
	 */
	public void rollBack() {
		transaction.rollback();
	}
	/**
	 * selectByQuery
	 * @param statement
	 * @return
	 */
	public JdbcManager<T> executeByQuery(String statement) {
		query = session.createQuery(statement);
		return this;
	}
	
	public JdbcManager<T> executeByQueryParams(String statement, HashMap<String, Object> params) {
		query = session.createQuery(statement);
		Set<String> keys = params.keySet();
		for(String key : keys) {
			query.setParameter(key, params.get(key));
		}
		return this;
	}
	@SuppressWarnings("unchecked")
	public T selectByEntityClass (Class<T> entity, long pk) {
		return (T) session.get(entity, pk);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getListResult() {
		return this.query.list();
	}
	
	@SuppressWarnings("unchecked")
	public T getSingleResult() {
		return (T) this.query.uniqueResult();
	}
	
	/**
	 * getObjectResult
	 * @return
	 */
	public Object getObjectResult() {
		return this.query.uniqueResult();
	}
	/**
	 * delete
	 * @return
	 */
	public int delete() {
		return this.query.executeUpdate();
	}
	
	/**
	 * delete 
	 * @param entity
	 * @param pk
	 */
	public void delete(Class<T> entity, long pk) {
		session.delete(selectByEntityClass(entity, pk));
	}
	
	public Integer insert(T entity) {
		return (Integer) session.save(entity);
	}
	
	public void update(T entity) {
		session.update(entity);
	}
	
	public JdbcManager() {
		session = HibernateSessionFactory.openSession();
	}
	
	/**
	 * closeSession
	 */
	public void closeSession() {
		if(NullCheckUtil.isNotNull(session)) {
			session.close();
			session = null;
		}
	}
}
